import Taro from '@tarojs/taro'
import {doAuth} from "../pages/auth/authFilter";

// 鉴权跳转
export async function navigateWithAuth(url) {
  if (await doAuth(url)) {
    return Taro.navigateTo({
      url
    })
  }
}

// 鉴权重定向
export async function redirectWithAuth(url) {
  if (await doAuth(url)) {
    return Taro.redirectTo({
      url
    })
  }
}

// 弹出无图标提示
export function toast(title) {
  return Taro.showToast({
    title,
    icon: 'none'
  })
}
//操作确认框
export async function showModal(title, content) {
  let flag = false
  await Taro.showModal({
    title: title,
    content: content,
  })
    .then(res => {
      flag = res.confirm
      console.log(res)
    })
  return flag
}
// 弹出成功消息
export function showSuccessMsg(message) {
  return Taro.atMessage({
    message,
    type: 'success',
  })
}

// 弹出错误消息
export function showErrorMsg(message) {
  return Taro.atMessage({
    message,
    type: 'error',
  })
}

// 返回主页
export function goHome() {
  return Taro.redirectTo({
    url: '/pages/guide/index'
  })
}

// 返回当前时间，格式yyyy-MM-dd hh:mm:ss
export function getFormatNowDate() {
  return getFormatDate(new Date());
}

// 格式化指定日期，格式yyyy-MM-dd hh:mm:ss
export function getFormatDate(date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${year}-${fillZero(month)}-${fillZero(day)} ${fillZero(hour)}:${fillZero(minute)}:${fillZero(second)}`;
}

function fillZero(num) {
  return num < 10 ? '0' + num : num;
}

function  setAuthorize (authorizeScope, modal) {
  return new Promise((resolve, reject) => {
    if (!modal) {
      modal = {
        title: '授权',
        content: '需要您设置授权已使用相应功能',
        confirmText: '设置'
      }
    }
    Taro.getSetting({
      success (res) {
        // hasAuthor === undefined  表示 初始化进入，从未授权
        // hasAuthor === true       表示 已授权
        // hasAuthor === false      表示 授权拒绝
        const hasAuthor = res.authSetting[authorizeScope]
        switch (hasAuthor) {
          case undefined:
            Taro.authorize({
              scope: authorizeScope,
              success: res => {
                resolve(res)
              },
              fail: err => {
                Taro.showToast({
                  title: '授权失败',
                  icon: 'none',
                  duration: 3000
                })
                reject(err)
              }
            })
            break
          case true:
            resolve()
            break
          case false:
            Taro.showModal({
              ...modal,
              success: res => {
                if (res.confirm) {
                  Taro.openSetting({
                    success: res => {
                      if (res.authSetting[authorizeScope]) {
                        resolve(res)
                      } else {
                        reject(res)
                        Taro.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 3000
                        })
                      }
                    },
                    fail: err => {
                      reject(err)
                      Taro.showToast({
                        title: '打开设置异常',
                        icon: 'none',
                        duration: 3000
                      })
                    }
                  })
                } else {
                  reject(res)
                  Taro.showToast({
                    title: '授权失败',
                    icon: 'none',
                    duration: 3000
                  })
                }
              },
              fail: err => {
                reject(err)
                Taro.showToast({
                  title: '弹窗异常',
                  icon: 'none',
                  duration: 3000
                })
              }
            })
            break
        }
      },
      fail: err => {
        reject(err)
        Taro.showToast({
          title: '获取当前设置异常',
          icon: 'none',
          duration: 3000
        })
      }
    })
  })
}
export function getLocation () {
  return new Promise((resolve, reject) => {
    const scope = 'scope.userLocation'
    const modal = {
      title: '授权',
      content: '需要您授权使用位置信息',
      confirmText: '设置'
    }
    setAuthorize(scope, modal)
      .then(() => {
        Taro.getLocation({
          altitude: true,
          success: res => {
            resolve(res)
          },
          fail: err => {
            reject(err)
            Taro.showToast({
              title: '获取位置信息失败',
              icon: 'none',
              duration: 3000
            })
          }
        })
      })
      .catch(err => {
        reject(err)
      })
  })
}
export function getDistance(lat1, lng1, lat2, lng2) {

  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;

  let rad1 = lat1 * Math.PI / 180.0;
  let rad2 = lat2 * Math.PI / 180.0;
  let a = rad1 - rad2;
  let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  let r = 6378137;
  return r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
}
